using HCore.Core;
using HCore.Unity.Core;
using JetBrains.Annotations;
using Session;
using UnityEngine;

namespace UI.UIGame.Menu.SortTile
{
    public class SortTileVisualButton : SessionHCoreMonoBehaviour
    {
        [SerializeField] public KeyCode KeyCode;
        [SerializeField] public SortPolicy SortPolicy;
        [SerializeField] public Sprite CursorSortIconSprite; // 鼠标排序图标精灵
        private FunctionUpdater mKeyCodeActionFunctionUpdater;

        /// <summary>
        ///     响应 排序按钮的点击事件
        /// </summary>
        private void ActionSortButton()
        {
            // 游戏会话还未成功初始化
            if (Session == null) return;

            // 正在预排序中
            if (Session.CurrentSortPolicy != SortPolicy.None)
            {
                // 点击了当前排序策略的按钮，则关闭预排序
                if (Session.CurrentSortPolicy == SortPolicy)
                {
                    PublishEvent(new SortStopCommand());
                }
                // 点击了其他的排序策略的按钮，则切换预排序（先关闭，再进入）
                else
                {
                    PublishEvent(new SortStopCommand());
                    PublishEvent(new SortPrepareCommand(SortPolicy, CursorSortIconSprite));
                }
            }
            // 没有进行预排序
            else
            {
                PublishEvent(new SortPrepareCommand(SortPolicy, CursorSortIconSprite));
            }
        }

        #region Unity Event

        protected override void Awake()
        {
            base.Awake();
            // 按钮点击监听器
            Get().AddButtonClickListener(ActionSortButton);
            // 快捷方式触发器
            mKeyCodeActionFunctionUpdater = GameUtils.CreateKeyCodeAction(KeyCode, ActionSortButton);
        }

        protected override void OnDestroy()
        {
            mKeyCodeActionFunctionUpdater.DestroySelf();
            base.OnDestroy();
        }

        #endregion
    }

    /// <summary>
    ///     停止排序指令
    /// </summary>
    [UsedImplicitly]
    public class SortStopCommand : Singleton<SortStopCommand>
    {
    }

    /// <summary>
    ///     准备开始排序
    /// </summary>
    [UsedImplicitly]
    public class SortPrepareCommand
    {
        public SortPrepareCommand(SortPolicy sortPolicy, Sprite cursorIconSprite)
        {
            SortPolicy = sortPolicy;
            CursorIconSprite = cursorIconSprite;
        }

        public SortPolicy SortPolicy { get; }
        public Sprite CursorIconSprite { get; }
    }
}